import logging
import os
import time
from datetime import datetime

from config import DEFAULT_DATE_FORMAT, BOOK_DATETIME_FORMAT


def basic_log_config(logDir='./logs', debug=True):
    """
    日志输出格式设定
    :param logDir:
    :param debug: 是否为DEBUG模式
    :return:
    """
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    if debug:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
    else:
        logFilename = os.path.join(logDir, time.strftime("%Y_%m_%d", time.localtime()) + '.log')
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=logFilename,
                            filemode='a')


def convert_date(dateStr):
    # Convert dateStr to Datetime, the format is DEFAULT_DATE_FORMAT = "%Y-%m-%d" OR
    # BOOK_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
    try:
        return datetime.strptime(dateStr, DEFAULT_DATE_FORMAT)
    except ValueError:
        try:
            return datetime.strptime(dateStr, BOOK_DATETIME_FORMAT)
        except ValueError:
            raise ValueError(
                f"Date string '{dateStr}' does not match known formats '{DEFAULT_DATE_FORMAT}' or '{BOOK_DATETIME_FORMAT}'")
